package com.zlq.cn.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zlq.cn.admin.service.SysConfigService;
import com.zlq.cn.api.ApiParam;
import com.zlq.cn.api.ApiResult;
import com.zlq.cn.api.SignApiResult;
import com.zlq.cn.cache.RedisCacheService;
import com.zlq.cn.cache.topic.RedisTopicService;
import com.zlq.cn.config.FinderConfiguration;
import com.zlq.cn.dto.DataCountDTO;
import com.zlq.cn.dto.DateCountDTO;
import com.zlq.cn.dto.vo.CommonConfuseToken;
import com.zlq.cn.entity.AppInfo;
import com.zlq.cn.entity.TPayReport;
import com.zlq.cn.mapper.un.FanyiUserMapper;
import com.zlq.cn.service.un.*;
import com.zlq.cn.util.DateUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import one.util.streamex.StreamEx;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Slf4j
@Api(tags = "公共")
@RestController
@AllArgsConstructor
@RequestMapping("/api/common")
public class CommonController {

    private final RedisCacheService redisCacheService;

    private final RedisTopicService redisTopicService;

    private final ConfigService configService;

    private final AppInfoService appInfoService;

    private final VipLogService vipLogService;

    private final VipOrderService vipOrderService;

    private final UserService userService;

    private final TPayReportService tPayReportService;

    private final FinderConfiguration configuration;

    private final CityOpenService cityOpenService;

    private final SysConfigService sysConfigService;

    private final FanyiUserMapper fanyiUserMapper;

    @GetMapping("/ossSts")
    public Object ossSts() {
        return configService.ossSts();
    }

    @ApiOperation("获取客户端开关信息")
    @GetMapping("/token")
    public SignApiResult<CommonConfuseToken> token(HttpServletRequest request) {
        CommonConfuseToken token = new CommonConfuseToken();
        token.setToken(UUID.randomUUID().toString().replace("-", ""));
        token.setExpireToken(sysConfigService.getById(SysConfigService.CONFIG_AES_LINK).getValueExt());
        boolean switchOpen = cityOpenService.checkOpen(request);
        token.setRefreshToken(switchOpen ? configuration.getSwitchYes() : configuration.getSwitchNo());
        return SignApiResult.resultSuccess(token);
    }

    @PostMapping("/appInfo")
    public Object appInfo(@RequestBody ApiParam apiParam, String bundleId, String version) {
        return appInfoService.lambdaQuery().eq(AppInfo::getBundleId, bundleId).eq(AppInfo::getAppVersion, version);
    }

    @GetMapping("/pay/report")
    public void payReport(String bundleId, String extParam) {
        TPayReport tPayReport = new TPayReport()
                .setReportTime(LocalDateTime.now())
                .setReportDate(LocalDate.now())
                .setBundleId(bundleId)
                .setExtParam(extParam);
        tPayReportService.save(tPayReport);
    }

    @GetMapping("/testPost")
    public Object testPost(String name, String age, String head) {
        redisCacheService.set("test", "123123");
        Object test = redisCacheService.get("test");
//        redisTopicService.aliPushBatteryWarningConvertAndSend("464464665");
        AppInfo appinfo = new AppInfo();
        appinfo.setCreateTime(LocalDateTime.now());
        appInfoService.save(appinfo);
        return "[{},{},{}]";
    }

    @GetMapping("/videos")
    public Object videos() {
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("image", "https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=1043662563,3219538677&fm=26&gp=0.jpg");
        jsonObject.put("url", "");
        jsonArray.add(jsonObject);
        jsonObject = new JSONObject();
        jsonObject.put("image", "https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=3207054189,273296922&fm=26&gp=0.jpg");
        jsonObject.put("url", "");
        jsonArray.add(jsonObject);
        return jsonArray;
    }

    @GetMapping("/totalCount")
    public Object totalCount() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("StatusCode", 200);
        LocalDateTime now = LocalDateTime.now();
        DateCountDTO dateCountDTO = new DateCountDTO();
        dateCountDTO.setStartTime(DateUtils.getDayMin(now.minusDays(7)));
        dateCountDTO.setEndTime(DateUtils.getDayMax(now));
        List<DataCountDTO> vipLogDataCountDTOS = vipLogService.totalCount(dateCountDTO);
        List<DataCountDTO> userDataCountDTOS = userService.totalCount(dateCountDTO);
        Map<String, Object> data = new HashMap<>();
        data.put("vips", vipLogDataCountDTOS);
        data.put("users", userDataCountDTOS);
        jsonObject.put("data", data);
        return jsonObject;
    }

    //    @RequestBody ApiParam apiParam,
//    @NotNull(message = "开始时间不能为空") LocalDateTime startTime,
//    @NotNull(message = "结束时间不能为空") LocalDateTime endTime
    @PostMapping("/vipTotal")
    public Object vipTotal(@RequestBody ApiParam apiParam) {
        return ApiResult.resultSuccess(vipLogService.vipLogTotal(DateUtils.getDayMin(apiParam.getObject("startTime", LocalDateTime.class)), DateUtils.getDayMax(apiParam.getObject("endTime", LocalDateTime.class))));
    }

    @PostMapping("/viplogDetails")
    public Object viplogDetails(@RequestBody ApiParam apiParam) {
        return ApiResult.resultSuccess(vipLogService.vipLogDetails(
                new Page<>(ObjectUtils.defaultIfNull(apiParam.getInteger("page"), 1), ObjectUtils.defaultIfNull(apiParam.getInteger("pageSize"), 10)),
                apiParam.getString("orderType"),
                DateUtils.getDayMin(apiParam.getObject("startTime", LocalDateTime.class)),
                DateUtils.getDayMax(apiParam.getObject("endTime", LocalDateTime.class))));
    }

    @GetMapping("/project/user/count")
    public Object projectUserCount(String day, String project) {
        if (StringUtils.isNotEmpty(project)) {
            project = StreamEx.split(project, ",")
                    .map(it -> String.format("'%s'", it))
                    .joining(",");
        }
        return fanyiUserMapper.projectUserCount(day, project);
    }

    @PostMapping("/project/vip/order")
    public Object projectVipOrder(@RequestBody ApiParam apiParam) {
        String bundleId = apiParam.getString("bundleId");
        LocalDateTime startTime = DateUtils.getDayMin(apiParam.getObject("startTime", LocalDateTime.class));
        LocalDateTime endTime = DateUtils.getDayMax(apiParam.getObject("endTime", LocalDateTime.class));
        return vipOrderService.vipOrderTotal(bundleId, startTime, endTime);
    }
}
